package com.qf.ithub.movie_demo01.service.impl;

import com.qf.ithub.common.exception.AppException;
import com.qf.ithub.common.result.ResponseEnum;
import com.qf.ithub.movie_demo01.entity.Role;
import com.qf.ithub.movie_demo01.entity.RoleExample;
import com.qf.ithub.movie_demo01.entity.User;
import com.qf.ithub.movie_demo01.entity.UserExample;
import com.qf.ithub.movie_demo01.entity.dto.RoleDTO;
import com.qf.ithub.movie_demo01.entity.dto.SearchDTO;
import com.qf.ithub.movie_demo01.mapper.RoleMapper;
import com.qf.ithub.movie_demo01.mapper.UserMapper;
import com.qf.ithub.movie_demo01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : xixi
 * @Title :
 * @date :  2021-03-18 08:26
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;


    /*查询所有的User*/
    @Override
    public List<User> getUser() {
        UserExample example = new UserExample();
        List<User> users = userMapper.selectByExample(example);
        return users;
    }

    @Override
    public User login(String userName,String userPassword) {
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(userName);
        List<User> users = userMapper.selectByExample(example);
        if(users==null || users.size()==0){
            throw new AppException(ResponseEnum.USERNAME_NOT_FOUND);
        }
        User user = users.get(0);
        if(userPassword.equals(user.getUserPassword()) == false){
            throw new AppException(ResponseEnum.USERNAME_OR_PASSWORD_INVALIDATE);
        }
        return user;
    }

    @Override
    public User getUserByid(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean checkUserName(String userName,Integer id) {
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(userName)
                .andIdNotEqualTo(id);
        int i = userMapper.countByExample(example);
        return i==0;
    }

    @Override
    public void updateUserByID(User user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<User> getUserBy(SearchDTO searchDTO) {
        List<User> users = userMapper.userSeach(searchDTO);
        return users;
    }

    @Override
    public void updateroleByID(Integer id,String roles) {
        User user = userMapper.selectByPrimaryKey(id);
        RoleExample roleExample=new RoleExample();
        roleExample.createCriteria().andRolenameEqualTo(roles);
        List<Role> list = roleMapper.selectByExample(roleExample);
        Integer roleid = list.get(0).getRoleid();
        user.setRoleid(roleid);
        user.setRoles(roles);
        userMapper.updateByPrimaryKeySelective(user);
    }



}
